package com.ywk.miaohsa.rabbitmq;

import com.ywk.miaohsa.domain.MiaoshaOrder;
import com.ywk.miaohsa.domain.MiaoshaUser;
import com.ywk.miaohsa.rabbitmq.message.MiaoshaMessage;
import com.ywk.miaohsa.redis.RedisService;
import com.ywk.miaohsa.result.CodeMsg;
import com.ywk.miaohsa.result.Result;
import com.ywk.miaohsa.service.GoodsService;
import com.ywk.miaohsa.service.MiaoshaService;
import com.ywk.miaohsa.service.OrderService;
import com.ywk.miaohsa.vo.GoodsVo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class MQReceiver {
    private static Logger log=LoggerFactory.getLogger(MQReceiver.class);

    @Autowired
    MiaoshaService miaoshaService;

    @Autowired
    GoodsService goodsService;

    @Autowired
    OrderService orderService;

    @RabbitListener(queues = MQConfig.QUEUE)
    public void receive(String message){
        log.info("receive message："+message);
    }

    @RabbitListener(queues = MQConfig.TOPIC_QUEUE1)
    public void receiveTopic1(String message){
        log.info("receiveTopic1 message："+message);
    }

    @RabbitListener(queues=MQConfig.TOPIC_QUEUE2)
    public void receiveTopic2(String message) {
        log.info(" topic  queue2 message:"+message);
    }

    @RabbitListener(queues=MQConfig.HEADER_QUEUE)
    public void receiveHeaderQueue(byte[] message) {
        log.info(" header  queue message:"+new String(message));
    }

    @RabbitListener(queues = MQConfig.MIAOSHA_QUEUE)
    public void MiaoshaReceive(String message){
        log.info("MiaoshaReceive message："+message);
        MiaoshaMessage msg=RedisService.stringToBean(message,MiaoshaMessage.class);
        MiaoshaUser user = msg.getUser();
        long goodsId = msg.getGoodsId();
        //判断库存
        GoodsVo goods = goodsService.getGoodsVoByGoodsId(goodsId);
        int stock = goods.getStockCount();
        if(stock <= 0) {
            return;
        }
        //判断是否已经秒杀到了
        MiaoshaOrder order = orderService.getMiaoshaOrderByUserIdGoodsId(user.getId());
        if(order != null) {
            return;
        }
        //减库存 下订单 写入秒杀订单
        miaoshaService.miaosha(user,goods);
    }
}
